<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.lineNumber" class="filter-item" clearable style="padding: 0;border-width: 0;" :placeholder="$t('equipment.lineNumber')" @change="handleFilter">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName+'_'+item.lineNumber" :value="item.lineNumber" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button> -->
    </div>
    <!-- 主界面数据 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('equipment.lineNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.lineName')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.location')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.location }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.priority')" prop="priority" width="150px" align="center">
        <template slot-scope="{row}">
          <el-rate v-model="row.priority" disabled :colors="['#99A9BF', '#99A9BF', '#F7BA2A', '#FF9900']" :max="5" style="margin-top:8px;" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.description')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.manager')" width="220px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.manager }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.lineNumber')" required prop="lineNumber">
          <el-input v-model="temp.lineNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.lineName')" required prop="lineName">
          <el-input v-model="temp.lineName" />
        </el-form-item>
        <el-form-item :label="$t('common.description')">
          <el-input
            v-model="temp.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
          />
        </el-form-item>
        <el-form-item :label="$t('equipment.location')">
          <el-input v-model="temp.location" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.manager')">
          <el-input v-model="temp.manager" clearable />
        </el-form-item>
        <el-form-item :label="$t('common.priority')">
          <el-rate v-model="temp.priority" :colors="['#99A9BF', '#99A9BF', '#F7BA2A', '#FF9900']" :max="5" style="margin-top:8px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLineList, creatLine, updateLine, deleteLine } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'LineDefinition',
  components: {
    Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      lineOptions: [],
      tableKey: 0,
      list: [],
      lineNumber: '',
      companylist: [],
      userlist: [],
      // 任务u状态
      stateOptions: [{ label: '所有', key: 0, color: 'white' },
        { label: '进行中', key: 1, color: 'green' },
        { label: '延期', key: 2, color: 'orange' },
        { label: '完成', key: 3, color: 'darkblue' },
        { label: '取消', key: 4, color: 'red' },
        { label: '暂停', key: 5, color: 'yellow' }],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineName: '',
        lineNumber: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      showReviewer: false,
      temp: {
        lineId: 0,
        lineNumber: '',
        description: '',
        lineName: '',
        manager: '',
        location: '',
        priority: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew'),
        company: '公司代号',
        manager: '人员信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        lineName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  created() {
    getLineList(this.listQuery).then(res => {
      this.lineOptions = res.data.lines
    })
    this.getList()
    this.lineNumber = this.$store.getters.lineNumber
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.list = response.data.lines
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 查看线体设备
    handleCheckLine(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/equipment/stationDef', query: { lineId: ret.lineId }})
    },
    // 查看错误信息
    handleCheck(row) {
      const ret = Object.assign({}, row) // copy obj
      if (ret.errMsg === null | '') {
        return
      }
      this.$msgbox({
        message: ret.errMsg,
        type: 'error'
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        lineId: 0,
        lineNumber: '',
        description: '',
        lineName: '',
        manager: '',
        location: '',
        priority: 0
      }
    },
    // 新建一条线体
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.manager = this.$store.getters.name
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatLine(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.$bus.$emit('getLineList')
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateLine(this.temp).then(response => {
            const index = this.list.findIndex(v => v.lineId === this.temp.lineId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteLine(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
            this.$bus.$emit('getLineList')
          })
        })
        .catch(err => { console.error(err) })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['项目号', '公司代号', '描叙', '优先级', '负责人', '启动', '交期', '状态', '创建时间', '备注']
        const filterVal = ['projectNo', 'companyCode', 'description', 'priority', 'manager', 'startDate',
          'dueDate', 'state', 'creatTime', 'remark']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '项目清单'
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
